package com.chanceit.ssss.fragments;

import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;

import net.tsz.afinal.http.AjaxCallBack;

import org.gl.GlobalVariable;
import org.gl.android.utils.SharePreferencesUtil;
import org.gl.customview.PullToRefreshView;
import org.gl.customview.search.MultiTypeSpinnerAutoComTextSearch;
import org.gl.utils.Tip;
import org.gl.utils.lg;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.os.Bundle;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TextView;
import android.widget.Toast;

import com.chanceit.ssss.activity.R;
import com.chanceit.ssss.button.GoAddCarButtonOnClickImp;
import com.chanceit.ssss.common.ActivityActionName;
import com.chanceit.ssss.common.IntentExtraDataKey;
import com.chanceit.ssss.common.IntentExtraDataKeyValue;
import com.chanceit.ssss.data.DataSources;
import com.chanceit.ssss.data.SearchCarer;

public class SearchCarerListFargment extends CarerListFragment implements
		SearchCarer<JSONArray> {
	int serchCondtionType = SearchCarer.Condition_Identifier;
	String[] type;
	View loading;
	AjaxCallBack<String> serchAjaxCallBack;
//	AjaxCallBack<String> exactSerchAjaxCallBack;
	@Override
	public JSONArray search(int conditionType, String value) {
		if (conditionType == type[0].hashCode()) {
			conditionType = SearchCarer.Condition_UserName;
		} else if (conditionType == type[1].hashCode()) {
			conditionType = SearchCarer.Condition_car_number;
			if (!TextUtils.isEmpty(value)&&value.length()>=3) {
				ds.searchUser(page, serchAjaxCallBack, conditionType, value);
			}else{
				Tip.show(getString(R.string.tip_length_three));
			}
			return null;
		} else if (conditionType == type[2].hashCode()) {
			conditionType = SearchCarer.Condition_Identifier;
		} else if (conditionType == type[3].hashCode()) {
			conditionType = SearchCarer.Condition_Tel_number;
		}
		if (contents!=null) {
			contents.removeAll(contents);
		}
		
		if (adapter!=null) {
			adapter.notifyDataSetChanged();
		}
		ds.exactSearchUser(page, serchAjaxCallBack, conditionType, value);
		return null;
	}

	TextView iv_err;
	View btn_addCarer;
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		serchAjaxCallBack = new AjaxCallBack<String>() {
			@Override
			public void onStart() {
				// TODO Auto-generated method stub
				super.onStart();
				loading.setVisibility(View.VISIBLE);
			}

			@Override
			public void onSuccess(String t) {
				if (getActivity()==null) {
					return;
				}
				if (t != null) {
					lg.i(TAG, "search result :"+t);
				} else {
					lg.i(TAG, "t ==null,no resule");
				}
				int code = 0;
				String mesage = "";
				try {
					JSONObject result = new JSONObject(t);
					code = result.optInt(webkey.code);
					mesage = result.optString(webkey.reason);

					JSONArray newJsonArray = result.optJSONArray(webkey.result);
					if (newJsonArray==null) {
						newJsonArray = new JSONArray();
					}
					contents.removeAll(contents);
					if (page <= 1) {// 如果当前页码为<=1 说明是第一次加载 清除以前的旧数据
						userListJosnAry = null;
						userListJosnAry = newJsonArray;
					} else {// 否则就是加载更多的分页数据,把新的数据添加到集合中
						for (int i = 0; i < newJsonArray.length(); i++) {
							userListJosnAry.put(newJsonArray.opt(i));
						}
					}
					int count = userListJosnAry.length();
					for (int i = 0; i < count; i++) {
						Map<String, Object> map = new HashMap<String, Object>();
						JSONObject temp = userListJosnAry.getJSONObject(i);
						for (String key : keys) {
							Object o = temp.opt(key);
							if (key.equals("carName")) {
								o = temp.optJSONObject("car").optString(
										"carName");
							} else if (key.equals("companyNick")) {
								o = temp.optJSONObject("company").optString(
										"companyNick");
							} else {
								o = temp.opt(key);
							}
							if (o == null || o.toString().equals("null")) {
								o = "";
							}
							map.put(key, o.toString());
						}
						contents.add(map);
					}
					if (adapter == null) {
						if (contents.size() > 0) {
							adapter = new SimpleAdapter(getActivity(),
									(List<Map<String, Object>>) contents,
									R.layout.list_item_carer, keys, new int[] {
											R.id.textView1, R.id.textView2,
											R.id.textView3, R.id.textView4,
											R.id.textView5 });
							setListAdapter(adapter);
						}
					} else {
						adapter.notifyDataSetChanged();
					}

					iv_err.setVisibility((contents.size() > 0) ? View.GONE
							: View.VISIBLE);
					btn_addCarer.setVisibility((contents.size() > 0) ? View.GONE
							: View.VISIBLE);
				} catch (JSONException e) {
					e.printStackTrace();
					mesage = e.getStackTrace().toString();
				} finally {
					page--;
					if (code != 0) {
						loadFailed(mesage);
					} else {
						loadSuccessed();
						page++;
					}
					loading.setVisibility(View.GONE);
				}

			}

			@Override
			public void onFailure(Throwable t, int errorNo, String strMsg) {
				super.onFailure(t, errorNo, strMsg);
				t.printStackTrace();
				loading.setVisibility(View.GONE);
				iv_err.setVisibility(View.VISIBLE);
				iv_err.setText(strMsg);
				btn_addCarer.setVisibility(View.VISIBLE);
			}
		};
	}
	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		view = inflater.inflate(R.layout.search_carer_list, container, false);
		ds = new DataSources();
		listView = (ListView) view.findViewById(R.id.order_carer_lv);
		iv_err = (TextView) view.findViewById(R.id.iv_err);
		btn_addCarer = view.findViewById(R.id.add_carer);
		btn_addCarer.setOnClickListener(new GoAddCarButtonOnClickImp(
				getActivity()));
		listView.setOnItemClickListener(this);
		mPullToRefreshView = (PullToRefreshView) (view
				.findViewById(R.id.main_pull_refresh_view));
		mPullToRefreshView.setOnHeaderRefreshListener(this);
		mPullToRefreshView.setOnFooterRefreshListener(this);
		loading = view.findViewById(R.id.loading);
		org.gl.customview.search.SearchAssistDirctionary _dictionary = new org.gl.customview.search.SearchAssistDirctionary();
		type = getResources().getStringArray(R.array.search_type);
		_dictionary.put(type[0], (HashSet<String>) SharePreferencesUtil.getStringSet(type[0]));
		_dictionary.put(type[1], (HashSet<String>) SharePreferencesUtil.getStringSet(type[1]));
		_dictionary.put(type[2], (HashSet<String>) SharePreferencesUtil.getStringSet(type[2]));
		_dictionary.put(type[3], (HashSet<String>) SharePreferencesUtil.getStringSet(type[3]));
		new MultiTypeSpinnerAutoComTextSearch((ViewGroup) view, getActivity(),
				_dictionary, this);
		return view;
	}

	@Override
	protected void initData(Integer _page) {
		if (adapter != null && userListJosnAry != null
				&& userListJosnAry.length() > 0) {
			setListAdapter(adapter);
			lg.i(TAG, "resotre the fragment");
			return;
		}
	}

	@Override
	protected void getData(Integer _page) {
		// TODO Auto-generated method stub
		super.getData(_page);
	}

	@Override
	public void onItemClick(AdapterView<?> arg0, View arg1, int position,
			long arg3) {
		// Set the item as checked to be highlighted when in two-pane layout
		listView.setItemChecked(position, true);
		
		try {
			IntentExtraDataKeyValue.updateUserInfoToIntent(userListJosnAry.getJSONObject(position).toString());
//			GlobalVariable.getGlobalInstance().intent.putExtra(
//					IntentExtraDataKey.USERID,
//					userListJosnAry.getJSONObject(position).optInt(
//							IntentExtraDataKey.USERID));
//			GlobalVariable.getGlobalInstance().intent.putExtra(IntentExtraDataKey.PLATE,
//					userListJosnAry.getJSONObject(position).optString(
//							IntentExtraDataKey.PLATE));
		} catch (JSONException e) {
			e.printStackTrace();
		} catch (NullPointerException e) {
			e.printStackTrace();
			Toast.makeText(getActivity(), "null user&plate", Toast.LENGTH_SHORT)
					.show();
		}
		int toGoType = GlobalVariable.getGlobalInstance().intent.getIntExtra(
				IntentExtraDataKey.SEARCHOFTYPE, 0);
		lg.e("GoSearchOnClickImp", ""+GlobalVariable.getGlobalInstance().intent.hashCode());
		switch (toGoType) {
		case IntentExtraDataKey.SEARCHOFTYPE_GO_PEOJECT:
			getActivity()
					.startActivityForResult(
							GlobalVariable.getGlobalInstance().intent
									.setAction(ActivityActionName.ORDER_RECEIVE),
							IntentExtraDataKey.ACTIVITY_QUESTCODE_UPDATECARERINFO);
			break;

		default:
			super.onItemClick(arg0, arg1, position, arg3);
			break;
		}
	}
}
